const mysql = require('mysql')
const fs = require('fs');
const path = require('path');
const moment = require('moment');
// 配置数据库链接
let db = null;
const logFilePath = path.join(__dirname, '../utils/error.log');
function initMysql(){
	db = mysql.createConnection({
		host:'127.0.0.1',
		user:'root',
		password:'root',
		port:3306,
		database:'qm_studentmanager',
		timezone: 'Asia/Shanghai'
	})
	db.connect(function(err){
		if(err){
			setTimeout(() => {
				initMysql
			}, 1000);
		}
	})
	db.on('error', function(err) {  
		console.error(err.code,21);  
		if(err.code==='PROTOCOL_CONNECTION_LOST'){
			initMysql()
		}else{
			throw err
		}
	  });
}
initMysql()
// 查询
const query = (sql,params)=>{
	return new Promise((resolve,reject)=>{
		db.query(sql,params,(err,resulte)=>{
			if(err){
				const errInfo = {
					timestamp: moment().format(),
					errorS:err
				};
				console.log(err,'数据库访问错误')
				fs.appendFileSync(logFilePath, JSON.stringify(errInfo) + '\n');
				reject(err)
			}else{
				resolve(resulte)
			}
		})
	})
}

module.exports = query